package com.cgy.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cgy.constant.FaceConstant;
import com.cgy.model.CallbackParam;
import com.cgy.model.CaptureLibResult;
import com.cgy.model.DataBean;
import com.cgy.model.Events;
import com.cgy.model.Faces;
import com.cgy.model.MsgSendData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * RabbitMqService
 *
 * @author think
 * @since 2024/1/28 16:34
 */
@Slf4j
@Service
public class RabbitMqService {

    @Autowired
    private IMessageService iMessageService;

    public void process(String originalData) {
        List<MsgSendData> imgList = extractImg(originalData);
        if (CollectionUtil.isNotEmpty(imgList)) {
            for (MsgSendData img : imgList) {
                iMessageService.sendMessage(FaceConstant.FTP_TOPIC_EXCHANGE_NAME, FaceConstant.FTP_TOPIC_ROUT_KEY_NAME,
                        JSON.toJSONString(img));
            }
        }
    }

    private List<MsgSendData> extractImg(String originalData) {
        CallbackParam callbackParam = JSONObject.parseObject(originalData, CallbackParam.class);
        List<MsgSendData> imgList = new ArrayList<>();
        if (!FaceConstant.METHOD_NAME.equals(callbackParam.getMethod()) || CollectionUtil.isEmpty(callbackParam.getParams().getEvents())) {
            return imgList;
        }
        List<Events> events = callbackParam.getParams().getEvents();
        for (Events event : events) {
            DataBean eventData = event.getData();
            List<CaptureLibResult> captureLibResult = eventData.getCaptureLibResult();
            if (CollectionUtil.isEmpty(captureLibResult)) {
                continue;
            }
            for (CaptureLibResult libResult : captureLibResult) {
                MsgSendData msgSendData = new MsgSendData();
                msgSendData.setImage(libResult.getImage());
                msgSendData.setRecvTime(eventData.getRecvTime());
                msgSendData.setDeviceId(event.getSrcIndex());
                msgSendData.setDeviceIndexCode(event.getSrcParentIndex());
                if (libResult.getFaces() != null) {
                    Faces faces = libResult.getFaces().get(0);
                    msgSendData.setGender(faces.getGender().getValue());
                }
                imgList.add(msgSendData);
            }
        }
        return imgList;
    }

}
